package fr.univ.colloque.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class PoolConnexion
{

    private String jndi = "jdbc/Colloque";
    private static PoolConnexion pool;

    private PoolConnexion()
    {
    }

    public static PoolConnexion getInstance()
    {
        if (pool == null)
        {
            pool = new PoolConnexion();
        }

        return pool;
    }

    public Connection getConnexion()
    {
        Context initCtx = null;
        DataSource ds = null;
        Connection con = null;
        try
        {
            initCtx = new InitialContext();
            ds = (DataSource) initCtx.lookup("java:comp/env/" + jndi);
            if (ds != null)
            {
                con = ds.getConnection();
            }

        }
        catch (NamingException ex)
        {
            Logger.getLogger(PoolConnexion.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(PoolConnexion.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }

    public void fermerConnexion(ResultSet rs, Statement s, Connection con)
    {
        if (rs != null)
        {
            try
            {
                rs.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(PoolConnexion.class.getName()).log(Level.SEVERE, null, ex);
            }
            rs = null;
        }


        if (s != null)
        {
            try
            {
                s.close();
            }
            catch (SQLException e)
            {
            }
            s = null;
        }
        if (con != null)
        {
            try
            {
                con.close();
            }
            catch (SQLException e)
            {
            }
            con = null;
        }
    }
}
